import React, { useState } from 'react'
import { Form, Button, Input, Selector } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import '../assets/css/loginView.css'
import { alert } from 'antd-mobile/es/components/dialog/alert';
import store from '../redux/store';
import { saveMsgAvatar, saveToken } from '../redux/action';

export default function LoginView() {
  const [form] = Form.useForm()
  const [logFlag, setFlag] = useState(true)
  let registerFlag = true
  let loginFlag = true
  let [codeUrl, setUrl] = useState("http://127.0.0.1:8080/account/checkCodeImg")
  const navigate = useNavigate()
  let [userFlag, setUser] = useState(false)

  const checkPassword = () => {
    if (!form.getFieldValue().passWord) {
      registerFlag = false
      alert('密码不能为空')
    } else {
      return true
    }
  }

  const checkName = () => {
    let pattern = new RegExp(/^[\u4e00-\u9fa5]{2,4}$/, 'g')
    let flag = pattern.test(form.getFieldValue().userName)
    if (!flag) {
      registerFlag = false
      alert('用户名不能为空,并且为2-4位中文字符')
    } else {
      return true
    }
  }

  const checkPhoneNumber = () => {
    let pattern = new RegExp(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, 'g')
    let flag = pattern.test(form.getFieldValue().userPhone)
    if (!flag) {
      registerFlag = false
      alert('电话号码不能为空,并且格式正确')
    } else {
      return true
    }
  }

  const checkIdentity = () => {
    if (!form.getFieldValue().userStatus) {
      registerFlag = false
      alert('请选择身份')
    } else {
      return true
    }
  }

  const checkCode = () => {
    if (!form.getFieldValue().checkCode) {
      registerFlag = false
      alert('请输入验证码')
    } else {
      return true
    }
  }

  async function register() {
    registerFlag = checkName() && checkPassword() && checkPhoneNumber() && checkIdentity() && checkCode()
    if (registerFlag) {
      let orginaccount = form.getFieldValue()
      let account = {
        userName: orginaccount.userName,
        passWord: orginaccount.passWord,
        userPhone: orginaccount.userPhone,
        userStatus: orginaccount.userStatus[0],
        checkCode: orginaccount.checkCode
      }
      let word = account.userStatus === 0 ? "老板" : "大神"
      fetch('http://127.0.0.1:8080/account/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(account)
      }).then(res => res.json()).then(res => {
        // localStorage.setItem('token',res.data)
        store.dispatch(saveToken(res.data))
        if (res.code !== 1) {
          changeCodeImg()
          alert(res.msg)
        } else {
          navigate('/main/info', { state: { identity: word, name: account.userName } })
        }
      })
    }
  }

  function login() {
    loginFlag = checkName() && checkPassword()
    let loginAccount = form.getFieldValue()
    // console.log(loginAccount)
    if (loginFlag) {
      fetch('http://127.0.0.1:8080/account/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(loginAccount)
      }).then(res => res.json()).then(res => {
        if (res.code === 1) {
          store.dispatch(saveToken(res.data.jwt))
          let title = res.data.claims.loginStatus == 0 ? '员工列表' : '老板列表'
          store.dispatch(saveMsgAvatar(res.data.avator))
          // console.log(res.data.avator);
          navigate('/main/Center', { state: {title: title} })
        } else {
          alert(res.msg)
        }
      })
    }
  }

  function changeMode() {
    form.resetFields()
    setUser(false)
    setFlag(!logFlag)
  }

  const changeCodeImg = () => {
    setUrl("http://127.0.0.1:8080/account/checkCodeImg?" + new Date().getMilliseconds())
  }

  const checkUserName = async () => {
    if (!logFlag) {
      let res = await fetch("http://127.0.0.1:8080/account" + "?username=" + form.getFieldValue().userName).then(res => res.json())
      if (res.code !== 1) {
        setUser(true)
      } else {
        setUser(false)
      }
    }
  }

  return (
    <div>
      <div className="header">硅谷直聘</div>
      <img src={require('../assets/images/logo.webp')} width="100%" height="100%" alt="" />
      {/* <img src={require(testImgUrl)} width="200px" height="100px" alt="" /> */}
      <div className="formBox">
        <Form
          layout='horizontal'
          form={form}
          footer={
            <Button block type='submit' color='primary' size='large' onClick={() => {
              if (logFlag) {
                login()
              } else {
                register()
              }
            }}>
              {logFlag ? '登录' : '注册'}
            </Button>
          }
        >
          <Form.Item
            name='userName'
            label='用户名'
            rules={[{ required: true, pattern: new RegExp(/^[\u4e00-\u9fa5]{2,4}$/, 'g'), message: '用户名不能为空,并且为2-4位中文字符' }]}
          >
            <Input onBlur={() => { checkUserName() }} placeholder='请输入用户名' />
          </Form.Item>
          {userFlag && <p className='checkUser'>用户名已存在</p>}
          <Form.Item name='passWord' label='密码' rules={[{ required: true, message: '密码不能为空' }]}>
            <Input placeholder='请输入密码' />
          </Form.Item>
          {!logFlag && <Form.Item name='userPhone' label='电话号码' rules={[{ required: true, pattern: new RegExp(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, 'g'), message: '电话号码不能为空,并且格式正确' }]}>
            <Input placeholder='请输入电话号码' />
          </Form.Item>}
          {!logFlag && <Form.Item name="checkCode" label='验证码' rules={[{ required: true }]}>
            <Input placeholder='请输入验证码'></Input>
          </Form.Item>}
          {!logFlag && <img src={codeUrl} width="100px" hight="50px" alt="" style={{ marginLeft: "40%" }} onClick={() => { changeCodeImg() }} />}
          {!logFlag && <Form.Item name="userStatus" rules={[{ required: true }]}>
            <Selector
              columns={2}
              options={[
                { label: '老板', value: 0 },
                { label: '大神', value: 1 }
              ]}
            />
          </Form.Item>}
        </Form>
        <p className='btn' onClick={() => {
          changeMode()
        }}>去{logFlag ? '注册' : '登录'}</p>
      </div>
    </div >
  )
}
